﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TopShelf_WindowsServce.Common;

namespace KQFuJiaCompareService.Common
{
    public class MdbHelper
    {
        private OleDbConnection myConn;

        /// <summary>
        /// 初始化连接数据库
        /// </summary>
        /// <param name="address"></param>
        public MdbHelper(string hostIP,string address)
        {
            try
            {
                //创建一个 OleDbConnection对象
                string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + address;
                myConn = new OleDbConnection(strCon);
                myConn.Open();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLine(hostIP, "MdbHelper-----------初始化连接数据库连接失败:" + ex.Message);
            }
        }

        /// <summary>
        /// 关闭数据连接
        /// </summary>
        public void CloseConnection()
        {
            myConn.Close();
        }

        /// <summary>
        /// 读取mdb文件的TestData表的数据
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public DataTable getDataTable(string sql)
        {
            OleDbCommand db_Command = myConn.CreateCommand();
            db_Command.CommandText = sql;
            var reader = db_Command.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(reader);
            return dt;
        }

        public int UpdateMdb(string sql)
        {

            OleDbCommand db_Command = new OleDbCommand(sql, myConn);
            int res = db_Command.ExecuteNonQuery();
            return res;
        }
    }
}
